Introduction to Python Functions

Because copy-pasting code is so last semester

Danilo Freire

Emory University

February 07, 2025

Welcome to Python Functions!
Let’s Code Smarter 🧠

Today’s Journey

  • Why Functions? ♻️
  • [Function Anatomy] 🔍
  • [Parameters vs Arguments] ↔︎️
  • [Live Coding] 🎮
  • [Best Practices] ✅
  • [Q&A + Exercises] 🏋️

Why Functions?

The Repetition Nightmare 😱

# Bad Code Alert! 🚨
print("Welcome Alice!")
print("Welcome Bob!")
print("Welcome Charlie!")
# ... repeats 997 more times ...

Repetition

Problems: - 🤦 Error-prone updates - 📏 1000 lines of same code - 😵 Hard to maintain

Functions to the Rescue! 🦸

# Clean Solution ✨
def welcome(name):
    print(f"Welcome {name}!")

welcome("Alice")
welcome("Bob")
welcome("Charlie")

Benefits: - ♻️ Reusable code - 📦 Organized logic - 🔄 One change updates all - 📖 Readable structure

DRY Principle

Function Anatomy 🔍

Building Blocks of a Function

def calculate_bmi(weight, height):
    """Calculate Body Mass Index"""
    bmi = weight / (height ** 2)
    return bmi

Function Anatomy

Parameters vs Arguments ↔︎️

Parameters
(Recipe Ingredients)

def greet(name, greeting="Hello"):
    # name and greeting are parameters
    print(f"{greeting}, {name}!")

Arguments
(Actual Ingredients)

greet("Alice", "Hi")  # Positional
greet(greeting="Bonjour", name="Bob")  # Keyword

Parameters vs Arguments

Let’s Code Together! 🎮

Exercise 1: Area Calculator

def calculate_area(length, width):
    # Your code here...
    return ???

# Test cases
print(calculate_area(5, 4))  # Should return 20
print(calculate_area(3, 7))  # Should return 21
# Solution
def calculate_area(length, width):
    return length * width

Exercise 2: Smart Greeter 🤓

def create_greeting(name, age, city="Unknown"):
    # Return message like:
    # "Hello Alice (25) from Paris!"
    ???

print(create_greeting("Alice", 25, "Paris"))  
# "Hello Alice (25) from Paris!"
print(create_greeting("Bob", 30))  
# "Hello Bob (30) from Unknown!"
# Solution
def create_greeting(name, age, city="Unknown"):
    return f"Hello {name} ({age}) from {city}!"

Pro Tips & Pitfalls ⚠️

Best Practices ✅

  • Single Responsibility
    One function = One task

  • Meaningful Names
    calculate_tax() not do_stuff()

  • Docstrings 📄

    def convert_currency(amount, rate):
        """Convert amount using exchange rate
    
        Args:
            amount (float): Money to convert
            rate (float): Exchange rate
    
        Returns:
            float: Converted amount
        """
        return amount * rate

Common Pitfalls 🕳️

  1. Mutable Defaults

    # Dangerous 🚨
    def add_item(item, lst=[]):
        lst.append(item)
        return lst
    
    # Safe ✅
    def add_item(item, lst=None):
        lst = lst or []
        lst.append(item)
        return lst
  2. Return vs Print

    # Bad - Can't reuse value 🚫
    def double(x):
        print(x * 2)
    
    # Good - Returns value ✅
    def double(x):
        return x * 2

Quick Quiz! ❓

What does this print?

def mystery(x=[]):
    x.append(1)
    return x

print(mystery(), mystery())

Answer:
[1, 1] [1, 1]
Because default list is created once!


Next Steps 🚀

Keep Learning!

Coding Practice

Thank You! 😊

Questions?
Let’s Code!
Exercise Solutions


Appendix: Solutions

Area Calculator

def calculate_area(length, width):
    return length * width

Smart Greeter

def create_greeting(name, age, city="Unknown"):
    return f"Hello {name} ({age}) from {city}!"

Back to Start ```